/*
 * Project: BoboDesignPattern
 * 
 * File Created at 2019年12月31日
 * 
 * Copyright 2012 Greenline.com Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Greenline Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Greenline.com.
 */
package test.practice;

import java.util.Arrays;

/**
 * @Type A20191231_0101_0102_heapsort
 * @Desc
 * @author 52489
 * @date 2019年12月31日
 * @Version V1.0
 */
public class A20191231_0101_0102_heapsort {

    public static void main(String[] args) {
        int nums[] = { 3, 2, 1, 7, 8, 5, 6, 3 };
        for (int i = nums.length / 2 - 1; i >= 0; i--) {
            ajustHeap1(nums, i, nums.length);
        }
        System.out.println(Arrays.toString(nums));
        for (int i = 0; i < nums.length; i++) {
            int tmp = nums[0];
            nums[0] = nums[nums.length - i - 1];
            nums[nums.length - i - 1] = tmp;
            ajustHeap1(nums, 0, nums.length - i - 1);
        }

        System.out.println(Arrays.toString(nums));
    }

    /**
     * @param nums
     * @param i
     * @param j
     */
    private static void ajustHeap(int[] nums, int i, int length) {
        if (2 * i + 1 <= length - 1) {
            int tmp = nums[i];
            int maxChildIdx = 2 * i + 1;
            if (maxChildIdx + 1 <= length - 1 && nums[maxChildIdx] < nums[maxChildIdx + 1]) {
                maxChildIdx++;
            }
            if (tmp < nums[maxChildIdx]) {
                nums[i] = nums[maxChildIdx];
                nums[maxChildIdx] = tmp;
                ajustHeap(nums, maxChildIdx, length);
            }

        }

    }

    private static void ajustHeap2(int[] nums, int i, int length) {
        int k = i;
        while (2 * k + 1 <= length - 1) {
            int tmp = nums[k];
            int maxChildIdx = 2 * k + 1;
            if (maxChildIdx + 1 <= length - 1 && nums[maxChildIdx] < nums[maxChildIdx + 1]) {
                maxChildIdx++;
            }
            if (tmp < nums[maxChildIdx]) {
                nums[k] = nums[maxChildIdx];
                nums[maxChildIdx] = tmp;
                k = maxChildIdx;
            } else {
                break;
            }
        }
    }

    private static void ajustHeap1(int[] nums, int i, int length) {
        int tmp = nums[i];
        for (int k = 2 * i + 1; k < length; k = 2 * k + 1) {
            if (k + 1 <= length - 1 && nums[k] < nums[k + 1]) {
                k++;
            }
            if (tmp < nums[k]) {
                nums[i] = nums[k];
                i = k;
            } else {
                break;
            }
        }
        nums[i] = tmp;
    }

}
